package com.fausto.learnimprint.message.consumer

import com.fausto.learnimprint.log.Slf4j
import com.fausto.learnimprint.log.Slf4j.Companion.log
import com.fausto.learnimprint.mail.MailConstant
import com.fausto.learnimprint.mail.MailMessage
import com.fausto.learnimprint.mail.MailService
import com.fausto.learnimprint.message.MqConstant
import org.springframework.amqp.rabbit.annotation.RabbitHandler
import org.springframework.amqp.rabbit.annotation.RabbitListener
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.stereotype.Component

@Component
@RabbitListener(queues = [MqConstant.MAIL_QUEUE])
@Slf4j
class MailListener {

    @Autowired
    lateinit var mailSender: JavaMailSender

    @Autowired
    lateinit var mailMessage: MailMessage

    @Autowired
    lateinit var mailService: MailService


    @RabbitHandler
    fun executeSms(map: Map<String, String>) {
        val mail = map["mail"]
        val code = map["code"]
        try {
//            this.sendMail(mail, code);
            Thread.sleep(3000)
            mailService.updateMailSendState(mail.toString(), code.toString(), MailConstant.MAIL_STATE_OK)

            sendMail(mail!!, code!!)

            log.info("$mail-$code-发送成功")
        } catch (e: Exception) {
            mailService.updateMailSendState(mail.toString(), code.toString(), MailConstant.MAIL_STATE_ERROR)
            log.error(mail + code + "发送失败-" + e.message)
        }
    }

    private fun sendMail(mail: String, code: String) {
        //发送邮件
        mailSender.send(
            mailMessage.create(
                mail,
                "邮箱验证码",
                "邮箱验证码：" + code + "，" + MailConstant.EXPIRED_TIME + "分钟内有效"
            )
        )
    }
}